package com.unionfetch.content_home.ui.account

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.google.android.flexbox.FlexboxLayout
import com.unionfetch.content_home.R
import com.unionfetch.content_home.bean.AccountLeverInfo
import com.unionfetch.content_home.bean.LeverageVos
import com.unionfetch.content_home.bean.TraderAccountVos
import com.unionfetch.content_home.bean.request.ModifyLeverRequest
import com.unionfetch.content_home.contract.AccountContract
import com.unionfetch.content_home.presenter.AccountPresenter
import com.unionfetch.content_home.ui.dialog.CustomTipDialog
import com.unionfetch.content_home.ui.dialog.LeverSelectAccountDialog
import com.unionftech.common.R.*
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseMvpActivity
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.bean.toast
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.ProtocolUtil
import com.unionftech.common.utils.ToastUtils
import com.unionftech.common.utils.Utils

class ModifyLiveLeverActivity : BaseMvpActivity(), AccountContract.ILeverInfoView,
    AccountContract.IModifyLeverView {
    private val mBtnConfirm by lazy { findViewById<Button>(R.id.btn_confirm) }
    private val mTvLeverAgreementElement by lazy { findViewById<TextView>(R.id.tv_lever_agreement_element) }
    private val mTvLeverAgreementText by lazy { findViewById<TextView>(R.id.tv_lever_agreement_text) }
    private val mIvAgreement by lazy { findViewById<ImageView>(R.id.iv_agreement) }
    private val mFblLeverContainer by lazy { findViewById<FlexboxLayout>(R.id.fbl_lever_container) }
    private val mTvSelectLeverTitle by lazy { findViewById<TextView>(R.id.tv_select_lever_title) }
    private val mTvLever by lazy { findViewById<TextView>(R.id.tv_lever) }
    private val mTvLeverTitle by lazy { findViewById<TextView>(R.id.tv_lever_title) }
    private val mTvAllAccountNetUnit by lazy { findViewById<TextView>(R.id.tv_all_account_net_unit) }
    private val mTvAllAccountNetValue by lazy { findViewById<TextView>(R.id.tv_all_account_net_value) }
    private val mTvAllAccountNetValueTitle by lazy { findViewById<TextView>(R.id.tv_all_account_net_value_title) }
    private val mTvBalanceAndUnit by lazy { findViewById<TextView>(R.id.tv_balance_and_unit) }
    private val mTvAccountNo by lazy { findViewById<TextView>(R.id.tv_account_no) }
    private val mTvTradeAccountTitle by lazy { findViewById<TextView>(R.id.tv_trade_account_title) }
    private val mLlTradeAccountContainer by lazy { findViewById<LinearLayout>(R.id.ll_trade_account_container) }
    private val mCacheView = mutableListOf<View>()


    @InjectPresenter
    private lateinit var mAccountPresenter: AccountPresenter
    private var mAccountLeverInfo: AccountLeverInfo? = null
    private var mTradeNo: String = ""

    //账号选项
    private val mAccountList = mutableListOf<TraderAccountVos>()
    private var mAccountIndex = -1

    //杠杆选项
    private val mLeverList = mutableListOf<LeverageVos>()
    private var mLeverDataList = mutableListOf<Int>()
    private val mEnableIndexList = mutableListOf<Int>()
    private var mSelectIndex = -1


    companion object {

        private const val TAG = "ModifyLiveLeverActivity"
        private const val PARAMS_TRADE_NO = "params_trade_no"

        @JvmStatic
        fun startThis(context: Context, tradeNo: String) {
            Intent(context, ModifyLiveLeverActivity::class.java).apply {
                if (context !is Activity) {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                putExtra(PARAMS_TRADE_NO, tradeNo)
                context.startActivity(this)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun initLayout() = R.layout.activity_modify_live_lever
    override fun obtainIntentData(intent: Intent) {
        super.obtainIntentData(intent)
        mTradeNo = intent.getStringExtra(PARAMS_TRADE_NO) ?: ""
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mTvTradeAccountTitle.text = DynamicResourceManager.getString(string.trade_account)
        mTvAllAccountNetValueTitle.text =
            DynamicResourceManager.getString(string.all_account_net_value)
        mTvLeverTitle.text = DynamicResourceManager.getString(string.current_lever)
        mTvSelectLeverTitle.text = DynamicResourceManager.getString(string.select_lever)
        mTvLeverAgreementText.text =
            DynamicResourceManager.getString(string.have_read_lever_agreement)
        mTvLeverAgreementElement.text =
            DynamicResourceManager.getString(string.lever_agreement_element)
        mBtnConfirm.text = DynamicResourceManager.getString(string.confirm)
    }

    override fun setListener() {
        super.setListener()
        mLlTradeAccountContainer.setOnClickListener(this)
        mIvAgreement.setOnClickListener(this)
        mBtnConfirm.setOnClickListener(this)
    }

    private fun initTitleBar() {
        setBackText(
            DynamicResourceManager.getString(string.modify_trade_lever),
            mContext.resources.getColor(
                color.color_1C1D21
            )
        )
    }

    override fun setView() {
        super.setView()
        mBtnConfirm.isEnabled = false
        hideCenterTitle()
        initTitleBar()
        loadData()
    }

    override fun loadData() {
        super.loadData()
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        mAccountPresenter.queryLeverage(userToken, mTradeNo)
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.ll_trade_account_container -> {
                //展示账号选项
                showAccountSelectDialog()
            }

            R.id.iv_agreement -> {
                mIvAgreement.isSelected = !mIvAgreement.isSelected
                setButtonEnable()
            }

            R.id.btn_confirm -> {
                //提交杠杆修改
                submit()
            }
        }
    }

    private fun submit() {
        getRequestBean()?.also {
            val userToken = GlobalInfoManager.getInstance().getUserToken()
            mAccountPresenter.modifyLeverage(userToken, it)
        }
    }

    private fun getRequestBean(): ModifyLeverRequest? {
        if (mAccountIndex == -1) {
            return null
        }
        if (mSelectIndex == -1) {
            return null
        }
        if (!mIvAgreement.isSelected) {
            return null
        }
        val request = ModifyLeverRequest().apply {
            mAccountList.getOrNull(mAccountIndex)?.also {
                traderAccount = it.traderAccount
            }
            mLeverList.getOrNull(mSelectIndex)?.also {
                leverageId = it.id
            }
        }
        return request
    }

    private fun showAccountSelectDialog() {
        if (mAccountList.isEmpty()) {
            return
        }
        val dialog = LeverSelectAccountDialog(mContext)
        dialog.setTitle(DynamicResourceManager.getString(string.trade_account))
            .setSelectIndex(mAccountIndex).setItemData(mAccountList).setCallBack { index ->
                mAccountList.getOrNull(index)?.also {
                    mAccountIndex = index
                    updateAccountInfo(it)
                }
            }.show()
    }

    private fun setButtonEnable() {
        mBtnConfirm.isEnabled = mAccountIndex != -1
                && mSelectIndex != -1
                && mIvAgreement.isSelected
                && mAccountList[mAccountIndex].accountProfit.toDouble() > 0.0
    }

    private fun updateInfo(accountLeverInfo: AccountLeverInfo) {
        mAccountLeverInfo = accountLeverInfo
        accountLeverInfo.leverageVos?.also {
            mLeverList.clear()
            mLeverList.addAll(it)
        }
        accountLeverInfo.traderAccountVos?.also {
            mAccountList.clear()
            mAccountList.addAll(it)
        }
        mAccountList.getOrNull(0)?.also {
            mAccountIndex = 0
            updateAccountInfo(it)
        }
        //全部账号净值
        mAccountLeverInfo?.also {
            mTvAllAccountNetValue.text = it.accNumTotalProfit
            mTvAllAccountNetUnit.text = "USD"
        }
    }


    private fun updateAccountInfo(info: TraderAccountVos) {
        //交易账号信息
        mTvAccountNo.text = info.traderAccount
        mTvBalanceAndUnit.text = "${info.accountProfit} ${info.currency}"
        //当前杠杆
        mTvLever.text = "1:${info.leverage}"
        updateLeverItem(info.leverage)
        //若该账号为总净值为0，修改杠杆按钮置灰不可点击；
        setButtonEnable()
    }

    private fun updateLeverItem(currentLever: Int) {
        mLeverDataList.clear()
        mEnableIndexList.clear()
        mLeverList.forEachIndexed { index, leverageVos ->
            if (leverageVos.leverage == currentLever) {
                mEnableIndexList.add(index)
                if (mSelectIndex == index) {
                    mSelectIndex = -1
                }
            } else if (leverageVos.disabled) {
                mEnableIndexList.add(index)
                if (mSelectIndex == index) {
                    mSelectIndex = -1
                }
            }
            mLeverDataList.add(leverageVos.leverage)
        }
        obtainItemView()
        setViewData()
    }

    private fun obtainItemView() {
        while (mFblLeverContainer.childCount > mLeverDataList.size) {
            val view = mFblLeverContainer.getChildAt(0)
            mFblLeverContainer.removeView(view)
            if (view != null) {
                mCacheView.add(view)
            }
        }
        while (mFblLeverContainer.childCount < mLeverDataList.size) {
            var view: View? = mCacheView.getOrNull(0)
            if (view == null) {
                view = LayoutInflater.from(mContext)
                    .inflate(R.layout.layout_wv_select_lever_item, null)
                view!!.tag = ItemViewHolder(view)
            } else {
                mCacheView.remove(view)
            }
            val dp16 = mContext.resources.getDimension(dimen.dp_16)
            val widthPixels = mContext.resources.displayMetrics.widthPixels
            val width = (widthPixels - 4 * dp16) / 3.0f
            val layoutParams = FlexboxLayout.LayoutParams(
                width.toInt(), FlexboxLayout.LayoutParams.WRAP_CONTENT
            )
            mFblLeverContainer.addView(view, layoutParams)
        }
    }

    private fun setViewData() {
        mLeverDataList.forEachIndexed { index, data ->
            mFblLeverContainer.getChildAt(index)?.also { view ->
                val viewHolder = setItemSelectBg(view, index)
                viewHolder.mTvItemText.text = "1:${data}"
                view.setOnClickListener {
                    if (!Utils.isFastDoubleClick(it.id)) {
                        removeSelect(mSelectIndex)
                        mSelectIndex = index
                        selectItem(mSelectIndex)
                        setButtonEnable()
                    }
                }
            }
        }
    }

    private fun selectItem(index: Int) {
        val view = mFblLeverContainer.getChildAt(index)
        if (view != null) {
            val viewHolder = view.tag as ItemViewHolder
            viewHolder.mIvItemSelect.visibility = View.VISIBLE
            viewHolder.mTvItemText.isSelected = true
        }
    }

    private fun removeSelect(index: Int) {
        val view = mFblLeverContainer.getChildAt(index)
        if (view != null) {
            val viewHolder = view.tag as ItemViewHolder
            viewHolder.mIvItemSelect.visibility = View.GONE
            viewHolder.mTvItemText.isSelected = false
        }
    }


    private fun setItemSelectBg(view: View, index: Int): ItemViewHolder {
        val viewHolder = view.tag as ItemViewHolder
        if (mSelectIndex == index) {
            viewHolder.mIvItemSelect.visibility = View.VISIBLE
            viewHolder.mTvItemText.isSelected = true
        } else {
            viewHolder.mIvItemSelect.visibility = View.GONE
            viewHolder.mTvItemText.isSelected = false
        }
        if (mEnableIndexList.contains(index)) {
            view.isEnabled = false
            viewHolder.mTvItemText.isEnabled = false
        } else {
            view.isEnabled = true
            viewHolder.mTvItemText.isEnabled = true
        }
        return viewHolder
    }

    class ItemViewHolder(view: View) {
        private val itemView = view
        internal val mTvItemText: TextView by lazy { itemView.findViewById(R.id.tv_item_text) }
        internal val mIvItemSelect: ImageView by lazy { itemView.findViewById(R.id.iv_item_select) }
    }

    /**
     * 获取当前账号的杠杆信息
     */
    override fun handleLeverInfo(response: ResponseResult<AccountLeverInfo>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            response.data?.also {
                updateInfo(it)
            }
        } else {
            LogUtils.d(TAG, "handleLeverInfo error-->$response")
            response.toast()
        }
    }


    /**
     * 修改杠杆的网络接口回调
     */
    override fun handleModifyLever(response: ResponseResult<Any?>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            showApplySuccessDialog()
        } else {
            LogUtils.d(TAG, "handleModifyLever error-->$response")
            response.toast()
        }
    }

    private fun showApplySuccessDialog() {
        val tipDialog = CustomTipDialog(mContext)
        tipDialog.setTopRes(R.drawable.ic_circle_success)
            .setTitle(DynamicResourceManager.getString(string.application_successful))
            .setMessage(DynamicResourceManager.getString(string.please_wait_tips))
            .setConfirmText(DynamicResourceManager.getString(string.close))
            .setCallBack {
                finish()
            }.show()
    }

    override fun backPressed(): Boolean {
        showLeaveDialog()
        return true
    }

    /**
     * 屏蔽物理返回键
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    private fun showLeaveDialog() {
        val dialog = CustomTipDialog(mContext)
        dialog.setTopRes(R.drawable.ic_circle_warning)
            .setTitle(DynamicResourceManager.getString(mContext, string.confirm_leave))
            .setCancelText(
                DynamicResourceManager.getString(
                    mContext, string.cancel
                )
            ).setConfirmText(
                DynamicResourceManager.getString(
                    mContext, string.confirm
                )
            ).setCallBack { confirm ->
                if (confirm) {
                    finish()
                }
                dialog.dismiss()
            }.show()
    }


}